
package org.okkam.refine.commands;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;

//import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
//import org.apache.commons.math.stat.descriptive.rank.Median;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;

import com.google.refine.commands.Command;
import com.google.refine.ProjectManager;
import com.google.refine.model.Project;
import com.google.refine.model.ColumnModel;
import com.google.refine.model.Column;
import com.google.refine.model.Row;
import com.google.refine.browsing.Engine;
import com.google.refine.browsing.FilteredRows;
import com.google.refine.browsing.RowVisitor;
import com.google.refine.util.ParsingUtilities;
/**
 * 
 * Validates PartitaIVA in a column.
 *
 */
public class ValidatePartitaIVACommand extends Command {

    protected RowVisitor createRowVisitor(Project project, int cellIndex, List values)
            throws Exception {
        return new RowVisitor() {

            int cellIndex;
            List values;

            public RowVisitor init(int cellIndex, List<Float> values) {
                this.cellIndex = cellIndex;
                this.values = values;
                return this;
            }

            @Override
            public void start(Project project) {
                // nothing to do
            }

            @Override
            public void end(Project project) {
                // nothing to do
            }

            public boolean visit(Project project, int rowIndex, Row row) {
                try {
                    String val = (String) row.getCellValue(this.cellIndex);
                    this.values.add(val);
                } catch (Exception e) {
                }

                return false;
            }
        }.init(cellIndex, values);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    };

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            ProjectManager.singleton.setBusy(true);
            Project project = getProject(request);
            ColumnModel columnModel = project.columnModel;
            Column column = columnModel.getColumnByName(request.getParameter("column_name"));
            int cellIndex = column.getCellIndex();

            List values = new ArrayList();// list of okkam IDs to be deleted

            Engine engine = new Engine(project);
            JSONObject engineConfig = null;

            try {
                engineConfig = ParsingUtilities.evaluateJsonStringToObject(request.getParameter("engine"));
            } catch (JSONException e) {
                // ignore
            }

            engine.initializeFromJSON(engineConfig);

            FilteredRows filteredRows = engine.getAllFilteredRows();
            filteredRows.accept(project, createRowVisitor(project, cellIndex, values));

            Iterator<String> PartitaIVAIt = values.iterator();
            Set<String> invalidCF = new HashSet<String>();

            int rowIndexes = 0;

            while (PartitaIVAIt.hasNext()) {
                try {
                    rowIndexes++;
                    String partitaIVA = PartitaIVAIt.next();
                    if (!controllaIVA(partitaIVA) && !"".equals(partitaIVA)) {
                        invalidCF.add(partitaIVA);
                    }

                } catch (Exception e) {
                    System.out.println( e);
                }
            }

            JSONWriter writer = new JSONWriter(response.getWriter());
            Iterator<String> InvalidPartitaIVAIt = invalidCF.iterator();

            writer.object();
            int index = 0;
            ;
            String invalidPartitaIva = "";
            int count=0; //for too much results, max 15 p.Ivas per line
            while (InvalidPartitaIVAIt.hasNext()) {
                count++;
               if(count<15){
                   invalidPartitaIva += InvalidPartitaIVAIt.next() + " ";
               }
               else{
                   count =0;
                   invalidPartitaIva += InvalidPartitaIVAIt.next() + "<br>";
               }
               
               

            }
            
            writer.key("partitaIVA");
            writer.value(invalidPartitaIva);

            writer.endObject();

        } catch (Exception e) {
            respondException(response, e);
        } finally {
            ProjectManager.singleton.setBusy(false);
        }
    };

    public boolean controllaIVA(String pIVA) {
   //     if(pIVA.toString().startsWith("0"))
     //       return false;
        if((pIVA.toString().length() != 11 ) && isInteger(pIVA))
        return false;
        
        return true;
        
    }
    
    public boolean isInteger( String input )  
    {  
       try  
       {  
          Integer.parseInt( input );  
          return true;  
       }  
       catch( Exception e)  
       {  
          return false;  
       }  
    }  


}
